# coding:utf-8
# rauth.py

import os
import gtk
import threading
import signal

from win import *
from icon import *
from auth import auth
def stopSignal(signum,frame):
	rauth.quit()
def hupSignal(signum,frame):
	rauth.set_state(conn=False)
signal.signal(signal.SIGINT,stopSignal)   
signal.signal(signal.SIGHUP,hupSignal)

class AuthThread(threading.Thread):
	def __init__(self,state):
		threading.Thread.__init__(self)
		self.setDaemon(True)
		self.__state = state
	def run(self):
		try:
			rauth.win.set_state(self.__state)
			rauth.icon.set_state(self.__state)
			rauth.auth.auth(conn=self.__state)
			rauth.auth.set_state(self.__state)
		except ('AUTH_DONE','ACCOUNT_NOT_VALID'):
			opsite = not self.__state
			rauth.icon.set_state(opsite)
			rauth.win.set_state(opsite)
			rauth.auth.set_state(opsite)
			rauth.set_connState(opsite)

class Rauth():
	def __init__(self):
		self.__connState=False
		self.win=win
		self.icon=icon
		self.auth=auth
		self.icon.connect("activate",self.win.on_activate)
		self.icon.connect_item.connect("activate",self.set_state,None)
		self.icon.quit_item.connect("activate",self.quit)
		self.win.button_connect.connect("clicked",self.set_state,True)
		self.win.button_disconn.connect("clicked",self.set_state,False)

	def set_state(self,widget,state=None):
		if state == None:state = self.icon.connect_item.get_active()
		if state != self.get_connState():
			self.set_connState(state)
			gtk.gdk.threads_init()
			gtk.gdk.threads_enter()
			authd=AuthThread(state)
			authd.start()
			gtk.gdk.threads_leave()
		return False

	def set_connState(self,state):
		self.__connState=state
	def get_connState(self):
		return self.__connState


	def main(self):
		gtk.gdk.threads_init()
		gtk.gdk.threads_enter()
		gtk.main()
		gtk.gdk.threads_leave()

	def quit(self,widget):
		cmd = []
		if os.getuid != 0:
			cmd = ['gksu','--']
		cmd += ['killall','myxrgsu']
		os.system(" ".join(cmd))
		gtk.main_quit()

rauth = Rauth()
rauth.main()
